package com.opencart.web.controller.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.opencart.domain.Category;
import com.opencart.service.CategoryService;
import com.opencart.utils.web.pagination.Pager;
import com.opencart.web.validator.CategoryValidator;

@Controller
@RequestMapping(value = "/categories")
@SessionAttributes("category")
public class CategoriesController {
	@Autowired
	private CategoryService categoryService;

	@Autowired
	private CategoryValidator categoryValidator;

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public CategoryValidator getCategoryValidator() {
		return categoryValidator;
	}

	public void setCategoryValidator(CategoryValidator categoryValidator) {
		this.categoryValidator = categoryValidator;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(ModelMap model, Pager pager) {
		model.addAttribute("categories",
				this.getCategoryService().paginate(pager));
		return "categories/list";
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(Model model) {
		List<Category> categories = this.getCategoryService().findAll();
		Category category = new Category();

		model.addAttribute("category", category);
		model.addAttribute("categories", categories);

		return "categories/add";
	}

	@RequestMapping(value = "processAdd", method = RequestMethod.POST)
	public String processAdd(@ModelAttribute("category") Category category,
			BindingResult result, SessionStatus status, Model model) {
		categoryValidator.validate(category, result);
		if (result.hasErrors()) {
			List<Category> categories = this.getCategoryService().findAll();
			model.addAttribute("category", category);
			model.addAttribute("categories", categories);
			return "categories/add";
		} else {
			categoryService.saveOrUpdate(category);
			return "redirect:/categories/list";
		}

	}

}
